package com.java.process.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.auth.pojo.LoginUserInfoHelper;
import com.java.auth.service.SysUserService;
import com.java.common.utils.R;
import com.java.model.process.Process;
import com.java.model.process.ProcessRecord;
import com.java.model.process.ProcessTemplate;
import com.java.model.system.SysUser;
import com.java.process.mapper.ProcessMapper;
import com.java.process.service.MessageService;
import com.java.process.service.ProcessRecordService;
import com.java.process.service.ProcessService;
import com.java.process.service.ProcessTemplateService;
import com.java.vo.process.ApprovalVo;
import com.java.vo.process.ProcessFormVo;
import com.java.vo.process.ProcessQueryVo;
import com.java.vo.process.ProcessVo;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Service
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Process> implements ProcessService {

    @Autowired
    private ProcessMapper processMapper;

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ProcessTemplateService processTemplateService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProcessRecordService processRecordService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private MessageService messageService;

    @Override
    public IPage<ProcessVo> selectPage(Page<ProcessVo> pageParam, ProcessQueryVo processQueryVo) {

        IPage<ProcessVo> page  = processMapper.selectPage(pageParam,processQueryVo);
        return page;
    }

    /**
     * 流程部署
     * @param deployPath
     */
    @Override
    public void deployByZip(String deployPath) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(deployPath);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        //流程部署
        Deployment deploy = repositoryService.createDeployment().addZipInputStream(zipInputStream).deploy();

    }

    /**
     * 启动实例
     * @param processFormVo
     */
    @Override
    public void startUp(ProcessFormVo processFormVo) {
        //1.根据当前id获取用户信息
        SysUser sysUser = sysUserService.getById(LoginUserInfoHelper.getUserId());
        System.out.println("LoginUserInfoHelper.getUserId()"+LoginUserInfoHelper.getUserId());
        System.out.println("processFormVo"+processFormVo);
        //2.根据审批模板id获取模板信息
        ProcessTemplate processTemplate = processTemplateService.getById(processFormVo.getProcessTemplateId());
        //3.保存提交信息到业务表，oa_process
        Process process = new Process();
        BeanUtils.copyProperties(processFormVo,process);
        String workNo = System.currentTimeMillis() + "";
        process.setProcessCode(workNo);
        process.setUserId(LoginUserInfoHelper.getUserId());
        process.setFormValues(processFormVo.getFormValues());
        process.setTitle(sysUser.getName() + "发起" + processTemplate.getName() + "申请");
        process.setStatus(1);
        baseMapper.insert(process);
        //4.启动流程实例，设置流程定义key，业务key processId,流程参数from表单json数据转map集合
        String processDefinitionKey = processTemplate.getProcessDefinitionKey();
        String businessKey = String.valueOf(process.getId());
        //将表单数据放入流程实例中
        JSONObject jsonObject = JSONObject.parseObject(processFormVo.getFormValues());
        JSONObject formData = jsonObject.getJSONObject("formData");
        Map<String, Object> map = new HashMap<>();
        for(Map.Entry<String,Object> entry: formData.entrySet()){
            map.put(entry.getKey(), entry.getValue());
        }
        //流程参数
        Map<String, Object> variables = new HashMap<>();
        variables.put("data",map);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);

        //5.业务表关联当前流程实例id,查询下一个审批人，审批人可能有多个
        String processInstanceId = processInstance.getId();
        List<Task> taskList = this.getCurrentTaskList(processInstanceId);
        if (!CollectionUtils.isEmpty(taskList)) {
            List<String> assigneeList = new ArrayList<>();
            for(Task task : taskList) {
                SysUser user = sysUserService.getByUsername(task.getAssignee());
                assigneeList.add(user.getName());

                //推送消息给下一个审批人，后续完善
                messageService.pushPendingMessage(process.getId(), user.getId(), task.getId());
            }
            process.setDescription("等待" + StringUtils.join(assigneeList.toArray(), ",") + "审批");
        }
        process.setProcessInstanceId(processInstanceId);
        baseMapper.updateById(process);

        //记录操作行为
        processRecordService.record(process.getId(), 1, "发起申请");



    }

    /**
     * 查询代办任务列表
     * @param pageParam
     * @return
     */
    @Override
    public R findPending(Page<ProcessVo> pageParam) {
        //分页查询待办任务
        TaskQuery query = taskService.createTaskQuery().taskAssignee(LoginUserInfoHelper.getUsername()).orderByTaskCreateTime().desc();
        List<Task> taskList = query.listPage((int) ((pageParam.getCurrent() - 1) * pageParam.getSize()), (int) pageParam.getSize());
        long count = query.count();
        //最后返回对象集合
        List<ProcessVo> processVoList = new ArrayList<>();
        //遍历封装成processVo
        for(Task task:taskList){
            ProcessVo processVo = new ProcessVo();
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            if (processInstance == null) {
                continue;
            }
            //获取业务id即processId
            String businessKey = task.getBusinessKey();
            if (businessKey == null) {
                continue;
            }
            Process process = this.getById(Long.parseLong(businessKey));
            if(process!=null){
                BeanUtils.copyProperties(process,processVo);
            }else{
                continue;
            }

            processVo.setTaskId(task.getId());
            processVoList.add(processVo);
        }

        Page<ProcessVo> page = new Page<>(pageParam.getCurrent(), pageParam.getSize(),count);
        page.setRecords(processVoList);
        return R.ok(page);
    }

    /**
     * 审批详情返回map集合
     * @param id
     * @return
     */
    @Override
    public R show(Long id) {

        //1.根据流程id获取流程信息
        Process process = baseMapper.selectById(id);
        //2.根据流程id获取流程记录信息
        LambdaQueryWrapper<ProcessRecord> lambdaQueryWrapper=
                new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProcessRecord::getProcessId,id);
        List<ProcessRecord> processRecordList = processRecordService.list(lambdaQueryWrapper);

        //3.根据模板id查询模板信息
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());

        //4.判断当前用户是否可以审批
        //不能重复审批，可以看到信息的不一定可以审批
        boolean isApprove = false;
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        for(Task task:taskList){
            //判断任务审批人是否是当前用户
            if(task.getAssignee().equals(LoginUserInfoHelper.getUsername())){
                isApprove = true;
            }
        }

        //5.封装成map集合，返回
        Map<String,Object> map = new HashMap<>();
        map.put("process", process);
        map.put("processRecordList", processRecordList);
        map.put("processTemplate", processTemplate);
        map.put("isApprove", isApprove);
        return R.ok(map);
    }

    /**
     * 审批管理
     * 如果审批不通过，直接结束流程（说明：并行审批流程不能满足，我们的业务当前不需要并行处理）
     * @param approvalVo
     * @return
     */

    @Override
    public R approve(ApprovalVo approvalVo) {
        //1.从approvalVO获取任务id，根据任务id获取流程变量
        String taskId = approvalVo.getTaskId();
        Map<String, Object> variables = taskService.getVariables(taskId);
        for(Map.Entry<String,Object> entry:variables.entrySet()){
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }

        //2.判断状态值

        if(approvalVo.getStatus() == 1){
            //2.1 状态值=1 审批通过
            Map<String, Object> variable = new HashMap<>();
            taskService.complete(taskId,variable);
        }else{
            //2.2   = -1,驳回，审批拒绝
            this.endTask(taskId);
        }

        //3.记录审批过程信息，oa_process_record
        String description = approvalVo.getStatus().intValue() == 1 ? "已通过" : "驳回";
        processRecordService.record(approvalVo.getProcessId(),approvalVo.getStatus(),description);
        //4.查询下一个审批人
        Process process = baseMapper.selectById(approvalVo.getProcessId());
        //查询任务
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        if(!CollectionUtils.isEmpty(taskList)){
            List<String> assignList = new ArrayList<>();
            for(Task task:taskList){
                String assignee = task.getAssignee();
                SysUser sysUser = sysUserService.getByUsername(assignee);
                assignList.add(sysUser.getName());
                //todo 公众号推送
                messageService.pushPendingMessage(process.getId(), sysUser.getId(), task.getId());
            }
            process.setDescription("等待" + StringUtils.join(assignList.toArray(), ",") + "审批");
            process.setStatus(1);
        }else{

            if(approvalVo.getStatus().intValue() == 1){
                process.setDescription("审批通过");
                process.setStatus(2);
            }else{
                process.setDescription("审批完成（驳回）");
                process.setStatus(-1);
            }
        }
        //推送消息给申请人
        //推送消息给申请人
        messageService.pushProcessedMessage(process.getId(), process.getUserId(), approvalVo.getStatus());
        this.updateById(process);

        return R.ok();
    }

    /**
     * 查看已处理任务
     * @param pageParam
     * @return
     */
    @Override
    public R findProcessed(Page<Process> pageParam) {
        //1.封装查询条件

        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(LoginUserInfoHelper.getUsername())
                .finished().orderByTaskCreateTime().desc();

        //2.调用方法条件分页查询，返回list集合
        //开始位置和分页数
        List<HistoricTaskInstance> list = query.listPage((int) ((pageParam.getCurrent() - 1) * pageParam.getSize()), (int) pageParam.getSize());
        long count = query.count();
        //遍历返回list集合，封装成List<ProcessVo>
        List<ProcessVo> processVoList = new ArrayList<>();
        for(HistoricTaskInstance item:list){
            //流程实例id
            String processInstanceId = item.getProcessInstanceId();
            //根据流程实例id获取process
            Process process = baseMapper.selectOne(new LambdaQueryWrapper<Process>().eq(Process::getProcessInstanceId, processInstanceId));
            ProcessVo processVo = new ProcessVo();
            if(process!=null){
                BeanUtils.copyProperties(process,processVo);
            }else{
                continue;
            }
            processVoList.add(processVo);
        }

        //IPage封装分页查询所有数据，返回

        Page<ProcessVo> page = new Page<>(pageParam.getCurrent(), pageParam.getSize(),count);
        page.setRecords(processVoList);
        return R.ok(page);
    }

    /**
     * 查询已发发起的任务
     * @param pageParam
     * @return
     */
    @Override
    public R findStarted(Page<ProcessVo> pageParam) {
        ProcessQueryVo processQueryVo = new ProcessQueryVo();
        processQueryVo.setUserId(LoginUserInfoHelper.getUserId());
        IPage<ProcessVo> page = processMapper.selectPage(pageParam, processQueryVo);
//        for (ProcessVo item : page.getRecords()) {
//            item.setTaskId("0");
//        }
        return R.ok(page);
    }

    private void endTask(String taskId) {
        //  当前任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        List endEventList = bpmnModel.getMainProcess().findFlowElementsOfType(EndEvent.class);
        // 并行任务可能为null
        if(CollectionUtils.isEmpty(endEventList)) {
            return;
        }
        FlowNode endFlowNode = (FlowNode) endEventList.get(0);
        FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());

        //  临时保存当前活动的原始方向
        List originalSequenceFlowList = new ArrayList<>();
        originalSequenceFlowList.addAll(currentFlowNode.getOutgoingFlows());
        //  清理活动方向
        currentFlowNode.getOutgoingFlows().clear();

        //  建立新方向
        SequenceFlow newSequenceFlow = new SequenceFlow();
        newSequenceFlow.setId("newSequenceFlowId");
        newSequenceFlow.setSourceFlowElement(currentFlowNode);
        newSequenceFlow.setTargetFlowElement(endFlowNode);
        List newSequenceFlowList = new ArrayList<>();
        newSequenceFlowList.add(newSequenceFlow);
        //  当前节点指向新的方向
        currentFlowNode.setOutgoingFlows(newSequenceFlowList);

        //  完成当前任务
        taskService.complete(task.getId());
    }

    /**
     * 获取当前任务列表
     * @param processInstanceId
     * @return
     */
    private List<Task> getCurrentTaskList(String processInstanceId) {

        List<Task> list = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        return list;
    }
}
